package com.qq.BFMRSE.extractWord;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.qq.BFMRSE.entity.PostStopAndLowCaseAnalyzer;

public class updateLucencHelper {
	public static boolean deleteLuIndex(String luIndexPath,String fileName){
		boolean ret=false;
		//Analyzer analyzer = new PostStopAndLowCaseAnalyzer();
		Analyzer analyzer = new StandardAnalyzer();  
		IndexWriterConfig iwc=new IndexWriterConfig(analyzer);
		Path indexPath=FileSystems.getDefault().getPath(luIndexPath);
		IndexWriter iWriter=null;
		Directory directory=null;
		try {
			directory=FSDirectory.open(indexPath);
			iWriter=new IndexWriter(directory,iwc);
			iWriter.deleteDocuments(new Term("path", fileName));
			iWriter.commit();
			//iWriter.close();
			System.out.println("文件删除完成。");
			ret=true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			if(iWriter!=null)
			{
				try {
					iWriter.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return ret;
	}
	/**
     * 删除索引
     */
    public static void delete(String luIndex,String deleteFileName) {
        IndexWriter indexWriter = null;
        try {
            Directory directory = FSDirectory.open(FileSystems.getDefault().getPath(luIndex));
            Analyzer analyzer = new StandardAnalyzer();
            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
            indexWriter = new IndexWriter(directory, indexWriterConfig);
            /**
             * 参数是一个选项，可以是一个Query，也可以是一个term，term是一个精确查找的值
             * 
             * 此时删除的文档并不会被完全删除，而是存储在一个回收站中的，可以恢复
             */

            // 方式一：通过Term删除

            /**
             * 注意Term构造器的意思，第一个参数为Field，第二个参数为Field的值
             */
            indexWriter.deleteDocuments(new Term("path",deleteFileName));


            // indexWriter.deleteDocuments(query);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (indexWriter != null) {
                    indexWriter.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
